package com.water.bs.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.water.bs.pojo.Photo;
import com.water.bs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;


@CrossOrigin
@RestController
public class PhotoController {
    @Autowired
    private UserService userService;

    @RequestMapping("/savePhoto")
    public JSON savePhoto(@RequestParam("file")MultipartFile file){
        System.out.println("图片接口");
        System.out.println(file);
        JSONObject rs = new JSONObject();
        Map<String,Object> photoMap = new HashMap<>();
        if (file.isEmpty()){
            rs.put("state","1");
            rs.put("message","上传失败,请重新选择!");
            return rs;
        }
        try {
            InputStream is = file.getInputStream();
            byte[] photoFile = new byte[(int)file.getSize()];
            System.out.println(file.getSize());
            is.read(photoFile);

            photoMap.put("photoFile",photoFile);
            photoMap.put("userid","testid");

            int i = userService.savePhoto(photoMap);
            if (i>0){
                rs.put("state","0");
                rs.put("message","保存成功");
            }else{
                rs.put("state","1");
                rs.put("message","上传失败!");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rs;
    }

    @RequestMapping("getPhoto")
    public void getPhoto(final HttpServletResponse response) throws IOException{
        Photo photo = userService.getPhoto("testid");
        byte[] data = photo.getPhotoFile();
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("UTF-8");
        OutputStream outputSream = response.getOutputStream();
        InputStream in = new ByteArrayInputStream(data);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len = in.read(buf, 0, 1024)) != -1) {
            outputSream.write(buf, 0, len);
        }
        outputSream.close();

    }
}
